import axios from 'axios'
import api from './Api'
import qs from 'qs'


// 新创建 axios 实例配置
const $axios = axios.create({
    baseURL: api.base,
    timeout: api.timeout,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})

$axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

$axios.interceptors.request.use((config) => {
  //在发送请求之前做某件事
  if(config.method  === 'post'){
    config.data = qs.stringify(config.data)
  }
  return config
},(error) =>{
  console.log("错误的传参")
  return Promise.reject(error)
})

$axios.interceptors.response.use((res) =>{
  console.log(res.data)
  //对响应数据做些事
  if(res.status != 200){
    return Promise.reject(res)
  }
  
  return res.data
}, (error) => {
  console.log("网络异常")
  //return Promise.reject(error)
})

export default {
  post(url, params) {
    console.info(`[post] ${api.base}${url}`)
    return new Promise((resolve, reject) => {
      $axios.post(url, params)
        .then(response => {
          resolve(response)
        }, err => {
          reject(err)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  
  get(url, params) {
    let data = null
    console.info(`[get] ${api.base}${url}`)
    return new Promise((resolve, reject) => {
      $axios.get(url, {params: params})
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
    })
  }
}